package com.cc.shop.web;

import com.cc.shop.dto.Result;
import com.cc.shop.entity.User;
import com.cc.shop.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Result<String > login(@RequestBody User user, HttpSession session){

        logger.info("========start========");
        long startTime = System.currentTimeMillis();
        user = userService.Login(user.getUsername(),user.getPassword());
        if (user!=null){
            session.setAttribute("user",user);
            logger.error("test error");
            long endTime = System.currentTimeMillis();
            logger.debug("costTime:[{}ms]",endTime-startTime);
            logger.info("========end========");
            return new Result<>(200,"登录成功！");
        }
        else{
            logger.error("test error");
            long endTime = System.currentTimeMillis();
            logger.debug("costTime:[{}ms]",endTime-startTime);
            logger.info("========end========");
            return new Result<>(201,"登录失败！");
        }

    }

    //用户注销
    @RequestMapping("/outLogin")
    @ResponseBody
    public Result<String> outLogin(HttpSession session){
        //通过session.invalidata()方法来注销当前的session
        session.invalidate();
        return new Result<>(200,"注销成功");
    }

    //用户注册
    @ResponseBody
    @RequestMapping(value="/regist",method=RequestMethod.POST)
    public Result<String> Regist(@RequestBody User user){
        try {
            if(userService.Check(user.getUsername())==null){
                userService.Regist(user.getUsername(),user.getPassword());
                return new Result<>(200,"注册成功");
            }else {
                return new Result<>(-1 ,"用户名已被注册");
            }

        }catch (Exception e){
            return new Result<>(201, e.toString() + e.getMessage());
        }
    }

}
